<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\controller\RedisAdmin;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Config;
use think\Controller;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\Log;
use think\Request;

class Schooldata extends Backend
{
    protected $user_id = 0;  //用户id
    protected $school_id = 0; //学校id

    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    public function _initialize()
    {
        parent::_initialize();
        $this->Collegial_model = new \app\admin\model\member\Collegial();
        $this->log_model = new \app\admin\model\SchoolData();
      //  $this->model = new \app\admin\model\Cms\Communication();
//        if($this->auth->type != '1'){
//            $this->error('该账号非正常老师账号');
//        }
//        $user_info = Db::name('admin')->where(['id'=>$this->auth->id])->field('s_id,type,user_id')->find();
////        if(empty($user_id)){
////            $this->error('该账号非正常老师账号');
////        }
////        var_dump($this->user_id);
//        $zd_user_info =  Db::name('zd_user')->where(['user_id'=>$user_id])->field('user_id,school_id')->find();
//        if(empty($zd_user_info)){
//            $this->error('账号信息有误，请核对后重试');
//        }
        $this->user_id =  $this->auth->user_id;
        $this->school_id = $this->auth->s_id;
    }

    public function index()
    {;
        $this->searchFields = 'school,province,location';
        $this->request->filter(['strip_tags']);
        $pid=input('pid')?input('pid'):'全部';
        $m_id= $this->auth->id;
        $province=get_pro_auth('extend/University',$m_id);//
        if (empty($province))$this->error('您无大学列表省份权限');
        if ($this->request->isAjax()) {
            //   $this->relationSearch = true;
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $pid=input('pid')?input('pid'):'全部';
            $where_new = ['is_lock'=>0];
            $con =[];
            $conn =[];

            if ($pid!='全部'){
                $con['b.province']=$pid;
                // $conn['province_id'] = get_province_id($pid);
            }else{
                $con['b.province']=['in',implode(",",array_column($province, 'name'))];;
                // $conn['province_id'] = get_province_id($pid);
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null,null,2);

            $count=$this->Collegial_model
                ->alias('b')
                ->where($where)
                ->where($where_new)
                ->where($con)
                ->count();
            $list=$this->Collegial_model
                ->alias('b')
                ->where($where)
                ->where($where_new)
                ->where($con)
                ->order('weight desc,id asc')
                ->limit($offset,$limit)
                ->select();
            $sql = $this->Collegial_model->getLastSql();


            foreach ($list as $w=>&$v){
            }
            $result = array("total" => $count, "rows" => $list,'sql'=>$sql);
            return json($result);
        }
        $this->assign('pid',$pid);
        $this->assign('province',$province);
        return $this->view->fetch();
    }

    /*
     * 渲染聊天界面
     */
    public function log()
    {
        $this->searchFields = 'school,province,location';
        $this->request->filter(['strip_tags']);
        $pid=input('pid')?input('pid'):'全部';
        $m_id= $this->auth->id;
        if ($this->request->isAjax()) {
            //   $this->relationSearch = true;
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $pid=input('pid')?input('pid'):'全部';
            $where_new = ['is_lock'=>0];
            $con =[];
            $conn =[];

            if ($pid!='全部'){
             //   $con['b.province']=$pid;
                // $conn['province_id'] = get_province_id($pid);
            }else{
            //    $con['b.province']=['in',implode(",",array_column($province, 'name'))];;
                // $conn['province_id'] = get_province_id($pid);
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null,null,2);

            $count=$this->log_model
                ->alias('b')
                ->where($where)
                ->where($con)
                ->count();
            $list=$this->log_model
                ->with(['school'])
                ->where($where)
                ->order('id asc')
                ->limit($offset,$limit)
                ->select();
            $sql = $this->log_model->getLastSql();

            foreach ($list as $w=>&$v){
            }
            $result = array("total" => $count, "rows" => $list,'sql'=>$sql);
            return json($result);
        }
        $this->assign('pid',$pid);
        return $this->view->fetch();
    }



    public function import()
    {
        ini_set('max_execution_time', '0');
        ini_set('memory_limit', '-1'); //内存 无限
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->Collegial_model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            // var_dump($allRow);
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }
          //  var_dump($fields);
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $cell = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow);
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    if($cell->getDataType() == DataType::TYPE_NUMERIC){
                        $cellstyleformat  =$cell->getStyle($cell->getCoordinate())->getNumberFormat();
                        $formatcode = $cellstyleformat->getFormatCode();
                        if(preg_match('/^(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy]/i',$formatcode)){

//                            $data=$val;//从excel导入后的时间
//                            $t = 24 * 60 * 60;
//                            $last_time = gmdate('Y-m-d H:i:s', ($data - 25569) * $t);
//                            var_dump($last_time);
                            $toTimestamp = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($val);
                            $num = 8*60*60;
                            $toTimestamp = $toTimestamp - $num;
                            $val = date("Y-m-d H:i:s", $toTimestamp );
                            $val = strtotime($val);

                        }
                    }
                    // var_dump($val);
                    $values[] = is_null($val) ? '' : $val;
                }
             //   var_dump($values);
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
//                        $new_where = [
//                            'school_name'=>$row['school_name'],
//                            'zy_name'=>$row['zy_name'],
//                            'pc'=>$row['pc'],
//                            'kl_name'=>$row['kl_name'],
//                        ];
//                        $update_data = [
//                            'lq_num2'=>$row['lq_num'],
//                            'letter2'=>$row['letter'],
//                            'letter_flag2'=>$row['letter_flag'],
//                            'pjf2'=>$row['pjf'],
//                            'update_time'=>time()
//                        ];
//                        $re = DB::name('cs_zy')->where($new_where)->update($update_data);
//                        if($re){
//                            unset($row[$fieldArr[$k]]);
//                        }
                    }
                }
              //  var_dump($row['zy_name']);
//                $zy_name = explode('(',$row['zy_name']);
//                $zy_names = explode($zy_name[0],$row['zy_name']);
//                $row['zy_name'] = $zy_name[0];
//                $row['cs_zy_name'] = $zy_names[1];
//                $cs_arr = '';
//                foreach ($zy_name as $w=>$v){
//                    if($w==0){
//                        $row['zy_name']  = $v;
//                    }else{
//                        $cs_arr .= $v;
//                    }
//                }
                //$row['cs_name'] = $cs_arr;
                //    var_dump($zy_name);exit;
                if ($row) {
                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage().$exception->getLine());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }

        try {
         //   var_dump($insert);
            foreach ($insert as $w=> &$val) {
                 $common_data = $val;
                $localAppData = Db::name('school_z')->where(['id'=>$val['id']])->find();
                $log = '';
                foreach($localAppData as $key => $v){
                    foreach ($common_data as $keys =>$vs){

                        if($key == 'school'  && $keys=='school'){
//                            var_dump($key);
//                            var_dump($v);
//                            var_dump($keys);
//                            var_dump($vs);
                        }
                        if($key == $keys && $v !=$vs ){
                            $log .= $key.'由'.$v.'更新为'.$vs.'--';
                            $update = [
                                $keys=>$vs
                            ];
                            $localAppData = Db::name('school_z')->where(['id'=>$val['id']])->update($update);
//                            var_dump($keys);
//                            var_dump($vs);
                        }
                    }

                }
                if($log != ''){
                    $log_data = [
                        'log'=>$log,
                        'school_id'=>$val['id'],
                        'create_time'=>time(),
                        'update_time'=>time(),
                    ];
                    Db::name('school_update_log')->insert($log_data);
                }

            }


////            var_dump(count($insert));
////            var_dump($insert);exit;
//
          //  $insert = array_values($insert);
         //   $this->Collegial_model->saveAll($insert);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }


    /**
     * 联动搜索
     */
    public function cx_province_select()
    {
        $type = $this->request->get('type');

        $group_id = $this->request->get('group_id');
        $list = null;
        if ($group_id !== '') {
            if ($type == 'group') {
//                $adminIds = \app\admin\model\CaAuthGroupAccess::where(['group_id'=>['in', [2,3]]])->column('uid');
//                // var_dump($adminIds);
//                $where = [
//                    'id'=>['in',$adminIds],
//                    'shop_name'=>['<>', ''],
//                    'status'=>'normal'
//                ];
                $where = [];
                $list = Db::name('province')->where($where)->field('id as value, name')->select();
                //     echo   Db::name('admin')->getLastSql();
//

            } else if($type == 'admin'){
                $where = [
                    'province_id' => $group_id,
                    'is_del' => 0,
                    //'status'=>'normal'
                ];
                $list =  Db::name('province_city')->where($where)->field('id as value, city AS name')->select();
//                foreach ($list as $w=>&$v){
//                    $v['value'] =  Db::name('user')->where(['admin_id'=>$v['value']])->value('id');
//                }
            } else {
                $where = [
                    'city_id' => $group_id,
                    //'status'=>'normal'
                ];
                $list =  Db::name('school_z')->where($where)->field('id as value, school AS name')->select();
//                foreach ($list as $w=>&$v){
//                    $v['value'] =  Db::name('user')->where(['admin_id'=>$v['value']])->value('id');
//                }
            }
        }
        $this->success('', null, $list);
    }
}
